import type {
  IMarkerIconExposedProps,
  IPoi,
  IPoiSearchResult,
} from "@/common/MapTypes";
import { reactive, type Ref } from "vue";
import { useMarkerStore } from "@/stores/useMarkerStore";
import { ResponseCode } from "@/common/Responsetypes";
import type { AMapCustomExposed } from "@/components/amapCustom/types";
import type { IPopupFlexExposed } from "@/components/popupFlex/types";

export default function (
  amapRef: Ref<AMapCustomExposed | null>,
  handleWriteJournal: () => void,
  popupFlexRef: Ref<IPopupFlexExposed | null>
) {
  const { addMarker, setActiveMarker } = useMarkerStore();

  const poiList: IPoiSearchResult = reactive({
    count: 0,
    pageIndex: 1,
    pageSize: 5,
    pois: [],
  });

  function setCenter(poi: IPoi) {
    amapRef.value?.setCenter(poi);
  }

  async function handleAddMarkerToMap(poi: IPoi) {
    uni.showLoading();
    const result = await addMarker(poi);

    if (result.code === ResponseCode.PASS) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      amapRef.value?.addMarkerToMap(result.data, {
        onClick(event: IMarkerIconExposedProps) {
          setActiveMarker(event);
          popupFlexRef.value?.close();
        },
      });
      uni.hideLoading();

      // 删除搜索结果中的 Marker
      amapRef.value?.delMarkerFromMap(poi, false);

      // 激活当前 marker
      setActiveMarker({
        container: null,
        poi: result.data,
      } as unknown as IMarkerIconExposedProps);

      uni.showToast({
        title: "添加成功",
        mask: true,
        duration: 1500,
        success() {
          setTimeout(() => {
            // 跳 添加文章页面
            handleWriteJournal();
          }, 1500);
        },
      });
    } else {
      uni.showToast({
        title: result.msg,
        mask: true,
      });
    }
  }

  return {
    poiList,
    setCenter,
    handleAddMarkerToMap,
  };
}
